
import datasource.localHttp as http
import pandas as pd
import time
class MaiRuiData:

    def __init__(self, update_interval=10):
        self.update_interval = update_interval  # 更新间隔（秒）
        self.is_trading = False
        self.last_data = {}
        self.callbacks = []

    # # 字段名称 数据类型 字段说明
    # # t string 交易时间
    # # o float 开盘价
    # # h float 最高价
    # # l float 最低价
    # # c float 收盘价
    # # v float 成交量
    # # a float 成交额
    # # pc float 前收盘价
    # # sf int 停牌 1 停牌，0  不停牌


    def mai_rui_data_k(self,stock_code,time_dimension,count=100,retry_count=3):
        # 使用示例
        # url = "https://api.mairuiapi.com/hsstock/history/603937.SH/5/n/6ED23952-8E9E-4755-8A05-8B426D33EF22?st=20251104133000&et=20251108093000&lt=100"
        url = f"https://y.mairuiapi.com/hsstock/history/{stock_code}/{time_dimension}/n/6ED23952-8E9E-4755-8A05-8B426D33EF22?st=20251004133000&et={get_14digit_timestamp()}&lt={count}"
        params = "" #{"symbol": "000001", "period": "daily"}
        for attempt in range(retry_count):
            try:
                df = http.api_to_dataframe(url, params)
                # 转换数据类型
                df['时间'] = pd.to_datetime(df['t'])
                df['开盘价'] = pd.to_numeric(df['o'])
                df['最高价'] = pd.to_numeric(df['h'])
                df['最低价'] = pd.to_numeric(df['l'])
                df['收盘价'] = pd.to_numeric(df['c'])
                df['成交量'] = pd.to_numeric(df['v'])
                df['成交额'] = pd.to_numeric(df['a'])
                return df

            except Exception as e:
                print(f"第{attempt + 1}次尝试失败: {e}")
                if attempt == retry_count - 1:
                    print(f"获取 {stock_code} 数据失败")
                time.sleep(1)

        return None

def get_14digit_timestamp() -> str:
    return time.strftime("%Y%m%d%H%M%S")